package com.dd.cloud.open.controller.api;

import com.dd.cloud.open.constants.HttpConstants;
import com.dd.cloud.open.enums.ResponseEnum;
import com.dd.cloud.open.exception.ApiException;
import com.dd.cloud.open.res.api.Response;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.StringUtils;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * @author zk
 */
@RestControllerAdvice("com.dd.cloud.open.controller.api")
public class ApiControllerAdvice {
    @ExceptionHandler(Exception.class)
    public Response<Object> handleException(Exception e) {
        e.printStackTrace();
        return new Response<>(ResponseEnum.SYSTEM_ERROR);
    }

    @ExceptionHandler(ApiException.class)
    public Response<Object> handleException(ApiException e) {
        e.printStackTrace();
        return new Response<>(e);
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Response<Object> handleException(HttpRequestMethodNotSupportedException e) {
        e.printStackTrace();
        int index = Objects.requireNonNull(e.getSupportedMethods()).length;
        String method;
        if (index == 1) {
            method = e.getSupportedMethods()[0];
            if (method.equals(HttpConstants.HTTP_METHOD_GET)) {
                return new Response<>(ResponseEnum.ONLY_ACCEPT_GET);
            } else if (method.equals(HttpConstants.HTTP_METHOD_POST)) {
                return new Response<>(ResponseEnum.ONLY_ACCEPT_POST);
            }
        }
        method = StringUtils.arrayToDelimitedString(e.getSupportedMethods(), ",");
        return new Response<>(ResponseEnum.ACCEPT_MULTIPLE_REQUEST_METHOD.getCode(), "接口接受" + method + "请求");
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Response<Object> handleException(HttpMessageNotReadableException e) {
        e.printStackTrace();
        return new Response<>(ResponseEnum.POST_BODY_RESOLVE_ERROR);
    }
}
